package main

import (
	"context"
	"database/sql"
	"fmt"
	"go-crud-demo/common"
	"go-crud-demo/controller"
	"go-crud-demo/middleware"
	"log"
	"net/http"

	_ "github.com/go-sql-driver/mysql"
)

const (
	user     = "root"
	password = 123456
	host     = "localhost"
	port     = 3306
	dbname   = "go_demo"
)

func init() {
	// 构建连接串
	// dsn := "root:123456@tcp(localhost:3306)/go_demo"
	dsn := fmt.Sprintf("%s:%d@tcp(%s:%d)/%s", user, password, host, port, dbname)

	// 打开数据库连接
	var err error
	common.Db, err = sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalln(err)
	}
	// defer common.Db.Close()

	ctx := context.Background()

	// 检查数据库连接是否成功
	err = common.Db.PingContext(ctx)
	if err != nil {
		log.Fatalln(err)
	}

	log.Println("Connected!")
}

func main() {
	server := http.Server{
		Addr:    ":8080",
		Handler: &middleware.AuthMiddleware{},
	}

	controller.RegisterRouter()

	log.Println("Server starting ...")
	server.ListenAndServe()
}
